<?php
/**
 * Created by PhpStorm.
 * User: lixiaohui
 * Date: 2015/9/22
 * Time: 18:35
 */

namespace Home\Controller;


use Think\Controller;
use Think\Log;

/**
 * Class PreSaveController
 * @package Home\Controller 预存controller
 */
class PreSaveController extends Controller
{
    //首页
    public function index()
    {
        $openId = getOpenId();
        $relevanceModel = M('member_relevance')->where("openid='%s'", $openId)->field('id,userid')->select();
        $this->assign("relevanceModel", $relevanceModel);
        $this->assign("bottomMenu", getBottomMenu());
        $this->display();
    }

    //预存充值清单详情
    public function detail()
    {
        $userid = I('userid');
        $infoArgs = array(
            "queryType" => "1",
            "queryKey" => $userid
        );
        //查询用户信息
        $postString = getPostString('GetUserInfo', $infoArgs);
        Log::write(C('INTERFACE_BASE_URL').'?'.$postString);
        //echo $postString;
        $retStr = post(C('INTERFACE_BASE_URL'), $postString);
        $retObj = json_decode($retStr, true);
        //dump($retObj);
        //获取最低充值金额
        $minSaveObj = json_decode(post(C('INTERFACE_BASE_URL'),getPostString('GetBjye',array("foo"=>"foo"))),true);
        $minSave = 0;
        if(intval($minSaveObj['retcode']) == 0){//获取失败
            $minSave = $minSaveObj['data']['list'][0]['bjye'];
        }
        //dump($minSave);
        $this->assign("json", $retObj['data']['list'][0]);
        $this -> assign('minSave',$minSave);
        $this->display();
    }

    /**
     * ajax 读取用户账户类型
     */
    public function checkAccount()
    {
        $userid = I('userid');
        $args = array(
            "queryType" => 1,
            "queryKey" => $userid
        );
        $postString = getPostString('GetUserInfo', $args);
        $retStr = post(C('INTERFACE_BASE_URL'), $postString);
        $retObj = json_decode($retStr, true);

        $this->ajaxReturn(array(
                "status" => 1,
                "accountType" => $retObj['data']['list'][0]['useratr'])
        );
    }


    //微信下单
    public function placeOrderInWeiXin(){
        $userid = I('userid');
        $totalFeeInFen = I('totalFee');

        Log::write("presave");

        if(intval($totalFeeInFen) < 0){
            $this -> ajaxReturn(array(
                "status"=>"fail",
                "msg"=>"支付金额应大于0"
            ));
        }
        $notifyUrl = C('NOTIFY_URL');//微信回调url
        $outTradeNo = $userid . date("YmdHis");
        Log::write($outTradeNo);

        $tools = getTools();
        $openId = getOpenId();

        $input = new \WxPayUnifiedOrder();
        $input->SetBody("预存水费");
        $input->SetAttach("预存水费");
        $input->SetOut_trade_no($outTradeNo);
        $input->SetTotal_fee(1);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("预存水费");
        $input->SetNotify_url($notifyUrl);
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($order);

        Log::write('order='.json_encode($order));
        Log::write('jsapiparameters='.json_encode($jsApiParameters));

        $chargeDate = date('Y-m-d H:i:s');

        //微信支付后调用该方法进行账单缴费
        $orderInfo = array(
            "userId"=>$userid,
            "outTradeNo"=>$outTradeNo,  //微信商户订单号
            "userAtr"=>2,//用户缴费属性 1-缴费用户,2-预存用户
            "tradeNo"=>"",//交易流水号
            "way"=>4,   //1-营业厅；2-自助终端；3-银联代扣；4-第三方代充
            "payType"=>3,   //1－现金；2－银联；3－微信；4－支付宝
            "payTime"=>$chargeDate,  //格式：yyyy-MM-dd hh:mm:ss
            "amount"=>$totalFeeInFen //支付总额，单位分
        );

        //生成订单保存订单表
        $saveOrder = array(
            "oriderID"=>$outTradeNo,    //订单号，此处保持微信商户订单号一致
            "ChargeDate"=>$chargeDate,  //日期
            "UserId"=>$userid, //水费账号
            "Amount"=>intval($totalFeeInFen),//充值金额
            "openID"=>getOpenId(),//微信openid
            "BusinessType"=>"2",//业务类型(1缴费 2预存)
            "TopupStatus"=>"1",//充值状态(0已支付，1未支付)
            "TopupType"=>"1",//充值类型(1微信充值)
            "refno"=>$outTradeNo //系统充值单号
        );
        Log::write(json_encode($saveOrder));
        $saveResult = M('order_info') -> add($saveOrder);
        if($saveResult < 0){//保存失败
            $this->ajaxReturn(array(
                "status"=>"fail",
                "msg"=>"后台提交订单失败!"
            ));
        }


        $this->ajaxReturn(array(
            "status"=>"success",
            "jsApiParameters"=>json_decode($jsApiParameters,true),
            "orderInfo"=>$orderInfo,
            "msg"=>"下单成功!"
        ));

    }

    //微信支付后调用该方法进行账单缴费
    public function Recharge(){
        $args = array(
            "userid"=>I('userId'),
            "useratr"=>I('userAtr'),
            "tradeno"=>I('tradeNo'),
            "way"=>I('way'),
            "paytype"=>I('payType'),
            "paytime"=>I('payTime'),
            "amount"=>intval(I('amount'))
        );
        Log::write('args='.json_encode($args));
        $postString = getPostString('Recharge',$args);
        Log::write('recharge'.$postString);
        $retStr = post(C('INTERFACE_BASE_URL'),$postString);
        Log::write('retStr='.$retStr);
        $this->ajaxReturn(array(
            "status"=>"success",
            "rechargeResult"=>json_decode($retStr,true)
        ));
    }

    //充值成功
    public function success()
    {
        $param = htmlspecialchars_decode(I('param'));
        $param = json_decode($param,true);
        //dump($param);
        $this -> assign('rechargeResult',$param);
        $this->display();
    }
}